import axios from "axios";
import router from "@/router";
import axiosRetry from "axios-retry"; // 需要安装此依赖
import { v4 as uuidv4 } from "uuid"; // 需要安装此依赖

// 请求队列管理
const pendingRequests = new Map();

// 创建 axios 实例
const service = axios.create({
  baseURL: import.meta.env.VITE_API_URL || "http://127.0.0.1:5000/api",
  headers: {
    "Content-Type": "application/json;charset=UTF-8",
  },
  timeout: 10000,
});

// 添加请求重试机制
axiosRetry(service, {
  retries: 3, // 重试次数
  retryDelay: (retryCount) => {
    return retryCount * 1000; // 重试延迟时间
  },
  retryCondition: (error) => {
    // 仅在网络错误或 5xx 错误时重试
    return (
      axiosRetry.isNetworkOrIdempotentRequestError(error) ||
      (error.response && error.response.status >= 500)
    );
  },
});

// 生成请求标识
const generateRequestKey = (config) => {
  const { method, url, params, data } = config;
  return `${method}-${url}-${JSON.stringify(params)}-${JSON.stringify(data)}`;
};

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    // 生成请求ID
    config.requestId = uuidv4();

    // 请求防重复 - 修改这部分逻辑
    const requestKey = generateRequestKey(config);
    if (pendingRequests.has(requestKey)) {
      const previousRequest = pendingRequests.get(requestKey);
      previousRequest.cancel("重复请求已取消");
      pendingRequests.delete(requestKey);
    }

    // 将新请求添加到队列
    const source = axios.CancelToken.source();
    config.cancelToken = source.token;
    pendingRequests.set(requestKey, source);

    // 请求日志记录
    console.log(`[Request] ${config.requestId}:`, {
      url: config.url,
      method: config.method,
      params: config.params,
      data: config.data,
      timestamp: new Date().toISOString(),
    });

    return config;
  },
  (error) => {
    console.error("请求拦截器错误:", error);
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    // 从队列中移除请求
    const requestKey = generateRequestKey(response.config);
    pendingRequests.delete(requestKey);

    // 响应日志记录
    console.log(`[Response] ${response.config.requestId}:`, {
      status: response.status,
      data: response.data,
      timestamp: new Date().toISOString(),
    });

    // 响应数据转换
    return transformResponse(response);
  },
  (error) => {
    // 从队列中移除请求
    if (error.config) {
      const requestKey = generateRequestKey(error.config);
      pendingRequests.delete(requestKey);
    }

    // 错误日志记录
    console.error(`[Error] ${error.config?.requestId}:`, {
      error: error.message,
      timestamp: new Date().toISOString(),
    });

    // 错误处理
    if (error.response) {
      switch (error.response.status) {
        case 401:
          handleUnauthorized();
          break;
        case 403:
          handleForbidden();
          break;
        case 429:
          handleTooManyRequests();
          break;
        default:
          handleOtherErrors(error);
      }
    } else if (error.request) {
      handleNetworkError(error);
    }

    return Promise.reject(error);
  }
);

// 响应数据转换器
const transformResponse = (response) => {
  const { data } = response;
  // 这里可以对响应数据进行统一转换
  return {
    ...response,
    data: {
      ...data,
      timestamp: new Date().toISOString(),
    },
  };
};

// 错误处理函数
const handleUnauthorized = () => {
  localStorage.removeItem("token");
  router.push("/login");
};

const handleForbidden = () => {
  console.error("禁止访问：您没有权限访问此资源");
};

const handleTooManyRequests = () => {
  console.error("请求过于频繁，请稍后再试");
};

const handleNetworkError = (error) => {
  console.error("网络错误:", error.message);
};

const handleOtherErrors = (error) => {
  console.error("其他错误:", error.message);
};

// 取消所有请求
export const cancelAllRequests = () => {
  for (const [key, source] of pendingRequests) {
    source.cancel("用户取消了请求");
    pendingRequests.delete(key);
  }
};

// 创建带有授权头的请求实例
export const requestWithAuth = (config) => {
  const token = localStorage.getItem("token");
  return service({
    ...config,
    headers: {
      ...config.headers,
      Authorization: `Bearer ${token}`,
    },
  });
};

export default service;
